import React, { useEffect, useRef, useState } from 'react';
import { Modal, message, Spin } from 'antd';
import { programDetail } from '../service';
import $ from 'jquery';
import styles from '../index.less';
import { TableListItem } from '../data.d';

interface PreviewProps {
  modalVisible: boolean;
  onCancel: () => void;
  values:TableListItem;
}

let width = '';
let height = '';
let resolution = 0;

//读取js文件
function readTextFile(file) {
  let str = "";
  let rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function () {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200 || rawFile.status == 0) {
        str = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
  return str;
}

function InnerHTML(props: any) {
  const divRef = useRef(null);
  const parent = props.parent;
  const id = parent.values.id;
  useEffect(() => {
    if(parent.modalVisible){
      if(id){
        new Promise((resolve, reject) => { //节目详情
          programDetail(id)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  let data = res.data;
                  const htmlStr = data.htmlStr;
                  const parsedHTML = document.createRange().createContextualFragment(htmlStr);
                  $(".previewContainer").append(parsedHTML);
                  $('#svgcontent').css({ width: '100%', height: 'auto' });
                  if($("foreignObject[tag='time'] .time").length>0){tick()}
                  resolve(true);
                } else {
                  message.error('请求失败，' + res.message);
                  resolve(false);
                }
                props.setSpinning(false);
              }
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      }
    }
  },[parent.modalVisible]);

  return <div className="previewContainer" ref={divRef}></div>;
}

const PreviewModel: React.FC<PreviewProps> = (props) => {
  const { modalVisible, onCancel, values } = props;
  const [spinning, setSpinning] = useState<boolean>(false);

  useEffect(() => {
    setSpinning(true);
  },[modalVisible]);
  
  if (Object.keys(values).length > 0) {
    width = values.resolutionWidth;
    height = values.resolutionHeight;
  }
  let p1 = 0;
  let p2 = width / height;
  if (p2 > 1) {
    p1 = document.body.clientWidth / width - 0.5;
  } else {
    p1 = document.body.clientHeight / height - 0.05;
  }
  resolution = p1 * width;
  return (
    <Modal
      className={styles.previewModel}
      destroyOnClose
      width={resolution}
      centered
      bodyStyle={{ padding: 0, lineHeight: 0 }}
      visible={modalVisible}
      footer={null}
      onCancel={onCancel}
    >
      <Spin spinning={spinning}>
        <InnerHTML parent={props} setSpinning={setSpinning}/>
      </Spin>
    </Modal>
  );
};

export default PreviewModel;
